package com.uzai.console.web.merchant;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.google.common.collect.Lists;
import com.uzai.common.enums.DeviceAuthTypeEnum;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.annotation.SystemLogType;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.CommonConstant;
import com.uzai.console.dto.BaseDto;
import com.uzai.console.dto.login.*;
import com.uzai.console.dto.module.merchant.GuideDto;
import com.uzai.console.dto.module.merchant.MerchantInfoDto;
import com.uzai.console.dto.sopmenu.SopMenuQuery;
import com.uzai.console.dto.sysmenu.SysMenuQuery;
import com.uzai.console.entity.*;
import com.uzai.console.enums.ContractStatusTypeEnum;
import com.uzai.console.enums.MerAccDetailSourceTypeEnum;
import com.uzai.console.enums.OperationTypeEnum;
import com.uzai.console.enums.SystemModelEnum;
import com.uzai.console.jsonvo.contract.ContractSignAddressJson;
import com.uzai.console.jsonvo.merbaseconfig.RealNameVerificationJson;
import com.uzai.console.mapper.*;
import com.uzai.console.service.merchant.CaptchaService;
import com.uzai.console.service.merchant.LoginService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.ratelimit.RatelimitService;
import com.uzai.console.service.sms.SmsService;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.login.PlatformMenuVo;
import com.uzai.console.vo.module.merchant.GuideVo;
import com.uzai.console.vo.module.merchant.MerchantLoginVo;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Auther: liuqi
 * @Date: 2021/08/12 16:43
 * @Description:
 */
@Api(value = "登录", tags = "登录")
@ApiSort(2)
@RestController
public class LoginController extends BaseController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private KefuUserMapper kefuUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private DeviceProductMapper deviceProductMapper;
    @Autowired
    private ProductAuthMapper productAuthMapper;
    @Autowired
    private DeviceTypeMapper deviceTypeMapper;
    @Autowired
    private ProductPriceMapper productPriceMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerAccDetailMapper merAccDetailMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private SopMenuMapper sopMenuMapper;

    @Autowired
    private SysContractMapper sysContractMapper;

    @ApiOperation(value = "短信验证码登录", notes = "短信验证码登录", response = LoginVo.class)
    @PostMapping("/loginByCode")
    public Object loginByCode(@RequestBody LoginByPhone loginByPhone) {
        LoginVo loginVO = loginService.loginByCode(loginByPhone);

        //将token存放cookie当中
        Cookie cookie = new Cookie(CommonConstant.TOKEN_HEADER, loginVO.getLoginToken());
        cookie.setMaxAge(24 * 3600);
        getResponse().addCookie(cookie);
        return loginVO;
    }

    @ApiOperation(value = "账号密码登录", notes = "账号密码登录", response = LoginVo.class)
    @PostMapping("/loginByPwd")
    public Object loginByPwd(@RequestBody LoginByPwd loginByPwd) {

        String mobile = loginByPwd.getMobile();
        String password = loginByPwd.getPassword();
        if(StringUtils.isBlank(mobile) || StringUtils.isBlank(password)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "登录账号和密码不能为空");
        }

        if(mobile.length() != 11 && mobile.length() != 23){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "登录账号格式不正确");
        }
        //验证客服账号登录
        if(mobile.length() == 23){
            String[] mobileStr = mobile.split("_");
            if(mobileStr != null && mobileStr.length == 2){
                loginByPwd.setMobile(mobileStr[0]);
                loginByPwd.setManagerMoblie(mobileStr[1]);
            }else{
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "登录账号格式不正确");
            }
        }

        //不是唐超账号或者系统通用密码
        if (!"15284924496".equals(loginByPwd.getMobile()) && !loginByPwd.getPassword().equals(DigestUtils.md5Hex(uzaiConsoleSysConfig.getDefaultPassword()))) {
            //滑块验证
            captchaService.authByCaptcha(loginByPwd.getNonceStr(), loginByPwd.getValue());
        }

        //不是客服账号登录
        LoginVo loginVO = null;
        if(StringUtils.isBlank(loginByPwd.getManagerMoblie())){
            loginVO = loginService.loginByPwd(loginByPwd);
        }else{//是客服账号登录
            loginVO = loginService.loginByKefu(loginByPwd);
        }
        //将token存放cookie当中
        Cookie cookie = new Cookie(CommonConstant.TOKEN_HEADER, loginVO.getLoginToken());
        cookie.setMaxAge(24 * 3600);
        getResponse().addCookie(cookie);
        return loginVO;
    }

    @ApiOperation(value = "发送短信验证码", notes = "发送短信验证码")
    @PostMapping("/getCode")
    public Object getCode(@RequestBody Code code) {
        if (code.getType() == 1) { //注册
            smsService.sms(code.getMobile(), code);
        }
        if (code.getType() == 2) { //登录

            //滑块验证
            String msg = captchaService.checkImageCode(code.getNonceStr(), code.getValue());
            if (StringUtils.isNotBlank(msg)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, msg);
            }

            //判断运营商是否存在
            merchantService.getByMobile(code.getMobile());
            smsService.sms(code.getMobile(), code);
        }

        if (code.getType().intValue() == -16) { //账户余额提现，不需要扣费
            //判断运营商是否存在
            merchantService.getByMobile(code.getMobile());
            smsService.sms(code.getMobile(), code);
        }

        if (code.getType() == 3 || code.getType() >= 5) { //扣费操作
            //判断运营商是否存在
            Merchant merchant = merchantService.getByMobile(code.getMobile());
            if (merchant == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERCHAT_UNREG);
            }

            //判断余额大小
            Double balance = merchant.getBalance();
            if (balance.doubleValue() < 0.1) { //不够支付
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足本次短信费用0.1元，请到【系统设置】/【账号设置】/【账户余额】处充值");
            }
            int now = DateUtil.getNowTime();
            //修改账户余额
            merchant.setBalance(balance - 0.1);
            merchant.setUpdateTime(now);
            int j = merchantMapper.updateBalance(merchant);
            if (j <= 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络异常");
            }
            //添加账户明细
            String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant.getBalance());
            merAccDetail.setCgMoney(0.1);
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.SMS_PAY.getId());
            merAccDetail.setSubtype("");
            merAccDetail.setTradeno(trandeNo);
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            merAccDetailMapper.insert(merAccDetail);

            //扣费成功才发送短信
            smsService.sms(code.getMobile(), code);
        }
        return true;
    }

    @ApiOperation(value = "发送短信验证码(扣除登录的操作员账户余额)", notes = "发送短信验证码(扣除登录的操作员账户余额)")
    @PostMapping("/getCodeChargeOperator")
    public Object getCodeChargeOperator(@RequestBody CodeChargeOperatorDto codeChargeOperatorDto) {
        if (codeChargeOperatorDto.getType() == 5) { //其他运营商配置方案复制敏感操作
            //判断运营商是否存在
            merchantService.getByMobile(codeChargeOperatorDto.getMobile());

            Merchant merchant_current = merchantMapper.selectById(codeChargeOperatorDto.getMerId());
            if (merchant_current == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERCHAT_UNREG);
            }

            //判断余额大小
            Double balance = merchant_current.getBalance();
            if (balance.doubleValue() < 0.1) { //不够支付
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足本次短信费用0.1元，请到【系统设置】/【账号设置】/【账户余额】处充值");
            }
            int now = DateUtil.getNowTime();
            //修改账户余额
            merchant_current.setBalance(balance - 0.1);
            merchant_current.setUpdateTime(now);
            int j = merchantMapper.updateBalance(merchant_current);
            if (j <= 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络异常");
            }
            //添加账户明细
            String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant_current.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant_current.getBalance());
            merAccDetail.setCgMoney(0.1);
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.SMS_PAY.getId());
            merAccDetail.setSubtype("");
            merAccDetail.setTradeno(trandeNo);
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            merAccDetailMapper.insert(merAccDetail);

            //扣费成功才发送短信
            Code code = new Code();
            code.setMobile(codeChargeOperatorDto.getMobile());
            code.setType(codeChargeOperatorDto.getType());

            smsService.sms(codeChargeOperatorDto.getMobile(), code);
        }

        return true;
    }

    @ApiOperation(value = "退出登录", notes = "退出登录")
    @PostMapping(value = "/logout")
    public Object logout() {
        //清空redis中的登录信息
        loginService.logout(getLoginInfo().getLoginToken());
        return true;
    }

    @ApiOperation(value = "查询当前登录账号信息", notes = "查询当前登录账号信息", tags = "系统设置", response = MerchantLoginVo.class)
    @PostMapping(value = "/getCurrentLoginInfo")
    public Object getCurrentLoginInfo() {
        //返回对象
        MerchantLoginVo merchantLoginVo = new MerchantLoginVo();

        merchantLoginVo.setId(getLoginInfo().getMerId());

        LoginVo loginVO = loginService.getLoginVoByToken(getLoginInfo().getLoginToken());
        if (loginVO != null) {
            //子账号
            if (loginVO.getType() == 1) {
                KefuUser kefuUser = kefuUserMapper.selectById(loginVO.getAccountId(), loginVO.getMerId());
                if (kefuUser != null) {
                    //查询子账号的主账号
                    Merchant merchant = merchantService.findByMerId(loginVO.getMerId());
                    if (merchant != null) {
                        BeanUtils.copyProperties(merchant, merchantLoginVo);
                    }
                    merchantLoginVo.setAccount(kefuUser.getUser());
                    merchantLoginVo.setAccountName(kefuUser.getName());
                    merchantLoginVo.setType(1);//子账号
                    merchantLoginVo.setHeadImg(kefuUser.getHeadImg());//子账号的头像
                    merchantLoginVo.setCreateTime(kefuUser.getCreateTime());
                    SysRole sysRole = sysRoleMapper.selectById(kefuUser.getRoleId(), kefuUser.getMerId());
                    //查询该子账号角色菜单权限
                    if (sysRole != null) {
                        merchantLoginVo.setAuthData(sysRole.getAuthData());
                    }
                }
            } else { //主账号
                Merchant merchant = merchantService.findByMerId(loginVO.getMerId());
                if (merchant != null) {
                    BeanUtils.copyProperties(merchant, merchantLoginVo);
                    merchantLoginVo.setType(0);//主账号
                    merchantLoginVo.setCreateTime(merchant.getCreateTime());
                }
            }

            //封装是否是合作伙伴
            String merchantPartnerFlag = "merchant_partner_flag_" + getLoginInfo().getMerId();
            Object val = redisTemplate.opsForValue().get(merchantPartnerFlag);
            if (val != null) {
                try {
                    merchantLoginVo.setPartnerLogoFlag(Integer.parseInt(val.toString()));
                } catch (Exception e) {
                }
            }

            //封装私域和功能模块的list（私域开启，功能模块开启且授权为到期）
            Set<String> appKeyList = new HashSet<>();
            //封装私域
            MerBaseConfig merBaseConfig_devices = merBaseConfigMapper.selectByMerId(loginVO.getMerId(), MerConfigKeyEnum.DEVICE_SWITCH.getValue());
            if (merBaseConfig_devices != null) {
                List<String> valList = JSONObject.parseArray(Tools.getStr(merBaseConfig_devices.getVal()), String.class);
                if (valList != null) {
                    for (String deviceTypeKey : valList) {
                        //判断此key是否在设备类型表中存在
                        DeviceType deviceType = deviceTypeMapper.selectByKey(deviceTypeKey);
                        if (deviceType != null) { //存在
                            appKeyList.add(deviceTypeKey);
                        }
                    }
                }
            }

            //封装产品功能模块
            MerBaseConfig merBaseConfig_product = merBaseConfigMapper.selectByMerId(loginVO.getMerId(), MerConfigKeyEnum.PRODUCT_SWITCH.getValue());
            if (merBaseConfig_product != null) {
                List<String> valList = JSONObject.parseArray(Tools.getStr(merBaseConfig_product.getVal()), String.class);
                if (valList != null) {
                    for (String productCode : valList) {
                        //判断此产品存不存在
                        Product product = productMapper.selectByCode(productCode);
                        if (product != null && product.getStatus().intValue() == 1) {//存在且有效，验证产品价格
                            ProductPrice productPrice = productPriceMapper.selectByProductCodeAndAuthType(product.getCode(), DeviceAuthTypeEnum.DAT_MONTH.getId());
                            if (productPrice != null) {
                                Double product_price = Tools.getDouble(productPrice.getPrice());
                                if (product_price.doubleValue() > 0.00) { //价格大于0的产品，需要判断授权时间是否到期
                                    ProductAuth productAuth = productAuthMapper.selectByMerIdAndProductCode(loginVO.getMerId(), productCode);
                                    if (productAuth != null) {
                                        Integer expireTime = Tools.getInteger(productAuth.getExpireTime());
                                        Integer now = DateUtil.getNowTime();
                                        if (expireTime > now) {//授权未到期
                                            appKeyList.add(productCode);
                                        }
                                    }
                                } else { //价格小于0的产品，直接加入菜单
                                    appKeyList.add(productCode);
                                }
                            }
                        } else {
                            //判断此设备产品存不存在
                            DeviceProduct deviceProduct = deviceProductMapper.selectByCode(productCode);
                            if (deviceProduct != null) {//存在，添加到设备产品的当中
                                appKeyList.add(productCode);
                            }
                        }
                    }
                }
            }

            //是否有SOP任务权限
            //不是以下2个运营商，则不允许添加
            if (Lists.newArrayList("13160220183", "15284924496", "13160220184", "13160206693").contains(loginVO.getMobile())) {
                appKeyList.add("cSMaintenanceSop");
            } else { //不是测试账号，则强制删除小程序、app
                appKeyList.remove("mini_pro");
                appKeyList.remove("app");
                //appKeyList.remove("tiktok");
            }

            //查询AOP权限
            SopMenuQuery sopMenuQuery = new SopMenuQuery();
            sopMenuQuery.setMerId(getLoginInfo().getMerId());
            List<SopMenu> sopMenuList = sopMenuMapper.findByList(sopMenuQuery);
            if (sopMenuList != null && sopMenuList.size() > 0) {
                for (SopMenu sopMenu : sopMenuList) {
                    appKeyList.add(sopMenu.getCode());
                }
            }

            //查询订单首单补贴权限
            MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(getLoginInfo().getMerId(), MerConfigKeyEnum.VIRTUAL_ORDER.getValue());
            if(merBaseConfig != null){
                appKeyList.add(merBaseConfig.getVal());
            }

            //封装权限表
            merchantLoginVo.setAppKeyList(appKeyList);

        }

        //查询向导功能配置
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(loginVO.getMerId(), MerConfigKeyEnum.GUIDE_CONFIG.getValue());
        if (merBaseConfig != null) {
            GuideVo guideVo = JSONObject.parseObject(merBaseConfig.getVal(), GuideVo.class);
            merchantLoginVo.setGuideVo(guideVo);
        } else {
            GuideVo guideVo = new GuideVo();
            merchantLoginVo.setGuideVo(guideVo);
        }

        //是否默认账户
        if (Tools.getLong(uzaiConsoleSysConfig.getDefaultMerId()).longValue() == merchantLoginVo.getId().longValue()) {
            merchantLoginVo.setDefaultAccount(1);
        }

        // 是否合同签约
        SysContract sysContract = sysContractMapper.selectByType(loginVO.getMerId(), ContractStatusTypeEnum.COMPLETE.getKey());
        merchantLoginVo.setContractSignFlag(sysContract == null ? 0 : 1);
        // 判断当前时间是否在5月月31号及之后
        boolean after = LocalDate.now().isAfter(LocalDate.of(2024, 5, 31));
        if (after && sysContract == null) {
            merchantLoginVo.setEnterSystemFlag(0);
        }
        // 是否签约中
        SysContract contractSigning = sysContractMapper.selectByType(loginVO.getMerId(), ContractStatusTypeEnum.UNDER_SIGNATURE.getKey());
        if (contractSigning != null) {
            merchantLoginVo.setContractSigningFlag(1);
        }
        return merchantLoginVo;
    }

    @SystemLogType(model = SystemModelEnum.SystemSet, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "账号设置", notes = "账号设置", tags = "系统设置")
    @PostMapping(value = "/updateLoginInfo")
    public Object updateLoginInfo(@RequestBody MerchantInfoDto merchantInfoDto) {
        //查询当前账号类型（0-主账号；1-子账号）
        LoginVo loginVo = getLoginInfo();

        merchantService.updateLoginInfo(merchantInfoDto, loginVo);
        return true;
    }

    @ApiOperation(value = "子账号密码登录", notes = "子账号密码登录", tags = "系统设置", response = LoginVo.class)
    @PostMapping("/loginByChildAccountPwd")
    public Object loginByChildAccountPwd(@RequestBody LoginByChildAccountPwdDto loginByChildAccountPwdDto) {
        LoginVo loginVO = loginService.loginByChildAccountPwd(loginByChildAccountPwdDto);

        //将token存放cookie当中
        Cookie cookie = new Cookie(CommonConstant.TOKEN_HEADER, loginVO.getLoginToken());
        cookie.setMaxAge(24 * 3600);
        getResponse().addCookie(cookie);
        return loginVO;
    }

    @ApiOperation(value = "悠聊账号密码登录", notes = "悠聊账号密码登录", tags = "系统设置", response = LoginVo.class)
    @PostMapping("/loginByUzaiAccountPwd")
    public Object loginByUzaiAccountPwd(@RequestBody LoginByUzaiAccountPwdDto loginByUzaiAccountPwdDto) {
        LoginVo loginVO = loginService.loginByUzaiAccountPwd(loginByUzaiAccountPwdDto);
        //将token存放cookie当中
        Cookie cookie = new Cookie(CommonConstant.TOKEN_HEADER, loginVO.getLoginToken());
        cookie.setMaxAge(24 * 3600);
        getResponse().addCookie(cookie);
        return loginVO;
    }

    @ApiOperation(value = "查询系统平台所有菜单", notes = "查询系统平台所有菜单", tags = "系统设置", response = PlatformMenuVo.class)
    @PostMapping("/findPlatformMenu")
    public Object findPlatformMenu(@RequestBody PlatformMenuDto platformMenuDto) {
        List<PlatformMenuVo> platformMenuVoList = new ArrayList<>();
        SysMenuQuery sysMenuQuery = new SysMenuQuery();
        sysMenuQuery.setAppKeyList(platformMenuDto.getAppKeyList());
        List<SysMenu> sysMenuList = sysMenuMapper.findByList(sysMenuQuery);
        if (sysMenuList != null && sysMenuList.size() > 0) {
            for (SysMenu sysMenu : sysMenuList) {
                PlatformMenuVo platformMenuVo = new PlatformMenuVo();
                platformMenuVo.setAppKey(sysMenu.getAppKey());
                platformMenuVo.setRoutes(JSONObject.toJSONString(sysMenu));
                platformMenuVoList.add(platformMenuVo);
            }
        }
        return platformMenuVoList;
    }

    /**
     * 敏感操作发送短信验证
     *
     * @param specialOperateSendSmsDto
     * @return
     */
    @ApiOperation(value = "敏感操作发送短信验证", notes = "敏感操作发送短信验证", tags = "系统设置", response = PlatformMenuVo.class)
    @PostMapping("/specialOperateSendSms")
    public Object specialOperateSendSms(@RequestBody SpecialOperateSendSmsDto specialOperateSendSmsDto) {
        merchantService.specialOperateSendSms(specialOperateSendSmsDto);
        return true;
    }

    @ApiOperation(value = "功能引导设置", notes = "功能引导设置", tags = "系统设置")
    @PostMapping(value = "/updateGuide")
    public Object updateGuide(@RequestBody GuideDto guideDto) {
        merchantService.updateGuide(guideDto);
        return true;
    }

    @ApiOperation(value = "修改密码", notes = "修改密码")
    @PostMapping(value = "/updatePassword")
    public Object updatePassword(@RequestBody PasswordUpdateDto passwordUpdateDto) {
        LoginVo loginVo = getLoginInfo();
        merchantService.updatePassword(passwordUpdateDto, loginVo);
        //清空redis中的登录信息
        loginService.logout(loginVo.getLoginToken());
        return true;
    }

    @ApiOperation(value = "发送运营商实名认证短信验证码", notes = "发送运营商实名认证短信验证码")
    @PostMapping(value = "/realName/getCode")
    public Object authenticationGetCode(@RequestBody RealNameGetCodeDto realNameGetCodeDto) {

        if (StringUtils.isBlank(realNameGetCodeDto.getPhone())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入手机号");
        }

        if (realNameGetCodeDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入验证码类型");
        }

        Merchant merchant_current = merchantMapper.selectById(realNameGetCodeDto.getMerId());
        if (merchant_current == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERCHAT_UNREG);
        }
        // 获取6月1号时间戳
        Long stamp = DateUtil.getLocalDateTimeStamp(LocalDateTime.of(2024, 6, 1, 0, 0));
        if (merchant_current.getRegTime() > stamp) {
            String  count = (String)redisTemplate.opsForValue().get(String.format(CacheKey.REQUEST_OVER_MAXCOUNT_SMS_MERID, realNameGetCodeDto.getMerId()));
            // 新用户如果次数为3次 则要扣费
            if (count != null && count.equals("3")) {
                //判断余额大小
                Double balance = merchant_current.getBalance();
                if (balance.doubleValue() < 0.1) { //不够支付
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足本次短信费用0.1元，请到【系统设置】/【账号设置】/【账户余额】处充值");
                }
                int now = DateUtil.getNowTime();
                //修改账户余额
                merchant_current.setBalance(balance - 0.1);
                merchant_current.setUpdateTime(now);
                int j = merchantMapper.updateBalance(merchant_current);
                if (j <= 0) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络异常");
                }
                //添加账户明细
                String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
                MerAccDetail merAccDetail = new MerAccDetail();
                merAccDetail.setId(IdWorker.getId());
                merAccDetail.setMerId(merchant_current.getId());
                merAccDetail.setOperateType(2);//支出
                merAccDetail.setMoney(merchant_current.getBalance());
                merAccDetail.setCgMoney(0.1);
                merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.SMS_PAY.getId());
                merAccDetail.setSubtype("");
                merAccDetail.setTradeno(trandeNo);
                merAccDetail.setCreateTime(now);
                merAccDetail.setUpdateTime(now);
                merAccDetailMapper.insert(merAccDetail);
                //扣费成功才发送短信
                Code code = new Code();
                code.setMobile(realNameGetCodeDto.getPhone());
                code.setType(realNameGetCodeDto.getType());
                smsService.sms(realNameGetCodeDto.getPhone(), code);
                return true;
            }
            //扣费成功才发送短信
            Code code = new Code();
            code.setMobile(realNameGetCodeDto.getPhone());
            code.setType(realNameGetCodeDto.getType());
            smsService.sms(realNameGetCodeDto.getPhone(), code);

            redisTemplate.opsForValue().set(String.format(CacheKey.REQUEST_OVER_MAXCOUNT_SMS_MERID,realNameGetCodeDto.getMerId()), count == null ? 1 : Integer.valueOf(count) + 1);
            return true;
        }
        //判断余额大小
        Double balance = merchant_current.getBalance();
        if (balance.doubleValue() < 0.1) { //不够支付
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足本次短信费用0.1元，请到【系统设置】/【账号设置】/【账户余额】处充值");
        }
        int now = DateUtil.getNowTime();
        //修改账户余额
        merchant_current.setBalance(balance - 0.1);
        merchant_current.setUpdateTime(now);
        int j = merchantMapper.updateBalance(merchant_current);
        if (j <= 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络异常");
        }
        //添加账户明细
        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        MerAccDetail merAccDetail = new MerAccDetail();
        merAccDetail.setId(IdWorker.getId());
        merAccDetail.setMerId(merchant_current.getId());
        merAccDetail.setOperateType(2);//支出
        merAccDetail.setMoney(merchant_current.getBalance());
        merAccDetail.setCgMoney(0.1);
        merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.SMS_PAY.getId());
        merAccDetail.setSubtype("");
        merAccDetail.setTradeno(trandeNo);
        merAccDetail.setCreateTime(now);
        merAccDetail.setUpdateTime(now);
        merAccDetailMapper.insert(merAccDetail);

        //扣费成功才发送短信
        Code code = new Code();
        code.setMobile(realNameGetCodeDto.getPhone());
        code.setType(realNameGetCodeDto.getType());
        smsService.sms(realNameGetCodeDto.getPhone(), code);

        return true;
    }

    @ApiOperation(value = "运营商实名认证", notes = "保存运营商实名认证", response = Boolean.class)
    @PostMapping(value = "/realName/verification")
    public Object realNameVerification(@RequestBody RealNameVerificationDto realNameVerificationDto) {
        merchantService.realNameVerification(realNameVerificationDto);
        return true;
    }

    @ApiOperation(value = "运营商实名认证并签署", notes = "保存运营商实名认证", response = ContractSignAddressJson.class)
    @PostMapping(value = "/realName/verificationAndSign")
    public Object realNameVerificationAndSign(@RequestBody RealNameVerificationDto realNameVerificationDto) {
        return merchantService.realNameVerificationAndSign(realNameVerificationDto);
    }

    @ApiOperation(value = "获取运营商实名认证信息", notes = "获取运营商实名认证信息", response = RealNameVerificationJson.class)
    @PostMapping(value = "/realName/getInfo")
    public Object getRealNameInfo(@RequestBody BaseDto baseDto) {
        return merchantService.getRealNameInfo(baseDto.getMerId());
    }
}
